/**
 * Simple cross-platform mutex library.
 * Adapted from:
 * http://www.codeproject.com/Articles/25569/Cross-Platform-Mutex
 */

#include "Mutex.h"

Mutex::Mutex()
{
#if defined(__unix__)
  pthread_mutex_init(&_mutex, NULL);
#elif defined(_WIN32)
  _mutex = CreateMutex(0, FALSE, 0);
#endif
}

Mutex::~Mutex()
{
#if defined(__unix__)
  pthread_mutex_destroy(&_mutex);
#elif defined(_WIN32)
  CloseHandle(_mutex);
#endif  
}

bool Mutex::lock()
{
#if defined(__unix__)
  return pthread_mutex_lock(&_mutex);
#elif defined(_WIN32)
  return (WaitForSingleObject(_mutex, INFINITE)==WAIT_FAILED ? 1 : 0);
#endif
}

bool Mutex::unlock()
{
#if defined(__unix__)
  return pthread_mutex_unlock(&_mutex);
#elif defined(_WIN32)
  return (ReleaseMutex(_mutex) == 0);
#endif
}

bool Mutex::trylock()
{
  // TODO: implement this function!
  return false;
}
